package com.example.lt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.lt.constant.MessageConstants;
import com.example.lt.entity.Captcha;
import com.example.lt.exception.RegisterException;
import com.example.lt.mapper.CaptchaMapper;
import com.example.lt.service.CaptchaService;
import com.example.lt.util.DateUtil;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.Date;

/**
 * @Author 小涛Tao
 * @Date: 2024/07/27/17:33
 * version 1.0 注释：生成图形验证码 和 邮箱验证码
 **/
@Service
public class CaptchaServiceImpl extends ServiceImpl<CaptchaMapper, Captcha> implements CaptchaService {

    @Autowired
    private Producer defaultKaptcha;

    /**
     * 生成图形验证码，并把验证码 code 、 uuid 和过期时间存储到数据库
     * @param uuid
     * @return
     */
    @Override
    public BufferedImage getCaptcha(String uuid) {
        // 生成验证码文本
        String code = defaultKaptcha.createText();
        Captcha captcha = new Captcha();
        captcha.setCode(code);
        captcha.setUuid(uuid);
        captcha.setExpireTime(DateUtil.addDateMinutes(new Date(), 5));
        this.save(captcha);
        return defaultKaptcha.createImage(code);
    }

    /**
     * 验证用户输入的图形验证码
     * @param captcha
     * @return
     */
    @Override
    public Boolean validate(Captcha captcha) {
        final String code1 = captcha.getCode();
        captcha = this.getOne(new LambdaQueryWrapper<Captcha>().eq(Captcha::getUuid, captcha.getUuid()));
        if (captcha == null) throw new RegisterException(MessageConstants.UUID_ISNULL);

        this.remove(new LambdaQueryWrapper<Captcha>().eq(Captcha::getUuid, captcha.getUuid()));

        // 验证码用户输入的图形验证码和系统生成的图形验证码是否相同
        if (!captcha.getCode().equals(code1)) throw new RegisterException(MessageConstants.CODE_ERROR);

        // 验证图形验证码是否过期
        if (captcha.getExpireTime().getTime() <= System.currentTimeMillis()) {
            throw new RegisterException(MessageConstants.CODE_EXPIRE);
        }

        if (!code1.equals(captcha.getCode())) return false;

        return true;
    }

    // 随机生成邮箱验证码
    public static String getSixCode(){
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int code = (int) (Math.random()*10);
            builder.append(code);
        }
        return builder.toString();
    }

}
